package edu.unlv.cs.ladders.entities;

import java.util.Calendar;
import java.util.HashSet;
import java.util.Set;
import edu.unlv.cs.ladders.entities.BaseEntity;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToOne;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;

import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.tostring.RooToString;
import org.springframework.roo.addon.entity.RooEntity;

@Entity
@RooJavaBean
@RooToString
@RooEntity(finders = { "findEventsByDateOfEventGreaterThanEquals", "findEventsByTournament", "findEventsByTournamentAndDateOfEventGreaterThanEquals", "findEventsByDateOfEventBetween" })
public class Event extends BaseEntity {

    private static final long serialVersionUID = 1L;

    private String note;

    @OneToOne(fetch = FetchType.EAGER)
    private Score challengerScore;

    @OneToOne(fetch = FetchType.EAGER)
    private Score defenderScore;

    @ManyToOne
    private Team challenger;

    @ManyToOne
    private Team defender;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private Set<Challenge> challengeHistory;

    @ManyToOne
    private Tournament tournament;

    @Temporal(TemporalType.DATE)
    @DateTimeFormat(style = "S-")
    private Calendar dateOfEvent;

    public Set<Challenge> getChallengeHistory() {
        if (this.challengeHistory == null) {
            this.challengeHistory = new HashSet<Challenge>();
        }
        return this.challengeHistory;
    }

    public void addChallenge(Challenge challenge) {
        if (!getChallengeHistory().contains(challenge)) {
            getChallengeHistory().add(challenge);
            this.merge();
        }
    }
    @Transient
    public Team getWinner(){
    	int compare = challengerScore.compareTo(defenderScore);
    	if(compare<0){
    		// the defender won
    		return defender;
    	} else if(compare>0){
    		// the challenger won
    		return challenger;
    	} else {
    		// there was a tie
    		return null;
    	}
    }
}
